package controlleur;

import exceptions.DataSourceException;
import exceptions.EmployeNotFoundException;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import modele.Employe;
import modele.InterfaceEmployeModel;
import org.apache.struts.action.*;

public class GetEmployeAction extends GenericAction {

    @Override
    public ActionForward execute(ActionMapping mapping,
                                 ActionForm form,
                                 HttpServletRequest request,
                                 HttpServletResponse response)
            throws IOException,
                   ServletException {
        ActionMessages errors = new ActionMessages();
        HttpSession session = request.getSession();
        ActionForward verif = null;
        String target = "success";

        // Teste sur l'identification de l'utilisateur
        if ((verif = verificationIdentification(mapping, request)) != null)
            return verif;

        // Annulation depuis la liste des employes
        if (isCancelled(request))
            return (mapping.findForward(target));

        try {
            InterfaceEmployeModel employeModel = getModel(request);
            Employe employe = employeModel.get(request.getParameter("username"));
            form = buildEmployeForm(employe);

            if (form != null)
                if ("request".equals(mapping.getScope()))
                    request.setAttribute(mapping.getAttribute(), form);
                else {
                    session = request.getSession();
                    session.setAttribute(mapping.getAttribute(), form);
                }
            else
                errors.add(ActionMessages.GLOBAL_MESSAGE,
                           new ActionMessage("errors.form.error"));

            employeModel.update(employe);
        } catch (EmployeNotFoundException e) {
            target = "error";
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                       new ActionMessage("errors.login.unknow", e.getMessage()));
        } catch (DataSourceException s) {
            target = "error";
            errors.add(ActionMessages.GLOBAL_MESSAGE,
                       new ActionMessage("errors.database.error"));
        }

        // Retourner les erreurs eventuelles
        if (!errors.isEmpty())
            saveErrors(request, errors);

        // Transmettre la requete a la vue appropriee
        return (mapping.findForward(target));
    }
}